<template>
    <div class="watchContainer">
        <!-- 连接后台的 -->
        <el-dialog 
            top="24vh" 
            v-model="linkVisable"
            :title="titleList[activeIndex - 1]"
            width="30%"
            center
            draggable
            @close="closeDialog"
        >
            <el-input v-model="store.userInfo.username" disabled v-if="activeIndex === 1" />
            <el-input v-model="linkCode" v-else></el-input>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="linkVisable = false" v-if="activeIndex === 1">取消</el-button>
                <el-button @click="beforeStep" v-else>上一步</el-button>
                
                <el-button type="primary" @click="confirmLink" v-if="activeIndex === 2">
                  确定
                </el-button>
                
                <el-button type="primary" @click="nextStep" v-else>
                  下一步
                </el-button>
            </span>
            </template>
        </el-dialog>
        <el-breadcrumb separator="/">
            <el-breadcrumb-item>首页</el-breadcrumb-item>
            <el-breadcrumb-item>数据监测</el-breadcrumb-item>
            <el-breadcrumb-item>监测管理</el-breadcrumb-item>
        </el-breadcrumb>
        <el-steps :active="activeIndex" v-if="stepVisable">
            <el-step title="Step 1" description="连接的用户名默认是登录用户名" />
            <el-step title="Step 2" description="设置连接码" />
            <el-step title="Step 3" description="连接成功" />
        </el-steps>
        <div class="tool">
            <el-button type="warning" @click="openWebsocket" v-if="!isWatch">开启数据监听</el-button>
            <el-button type="danger" @click="closeWebsocket" v-else>关闭数据连接</el-button>
        </div>

        <div class="table">
            <el-table 
                :data="deviceList"
                border 
                stripe 
           >
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="deviceName" label="设备编号"></el-table-column>
            <el-table-column prop="linkCode" label="连接码"></el-table-column>
            <el-table-column prop="linkTime" label="连接时间"></el-table-column>
            <el-table-column >
                <template #header>
                    设备类型
                </template>
                <template #default="{row}">
                    <el-tag class="ml-2" type="success" v-if="!row.type">电脑</el-tag>
                    <el-tag class="ml-2" type="info" v-else>手机</el-tag>
                    </template>
            </el-table-column>
            <el-table-column>
                <template #header>操作</template>
                <template #default="{row}">
                    <el-button type="danger" @click="closeLink(row.deviceName)">断开连接</el-button>
                </template>
            </el-table-column>
           </el-table>
        </div>
    </div>
</template>

<script setup lang="ts">
   import {ref,onMounted, reactive, getCurrentInstance} from 'vue'
   import {userStore} from '../../store/user'
   import { storeToRefs } from 'pinia'
   let {proxy} = getCurrentInstance()
   let activeIndex = ref(1)
   let stepVisable = ref(false)
   let titleList = [
     '连接的用户名',
     '连接码'
   ]
    let store = userStore()
    let {isWatch,linkCode,websocket,deviceList} = storeToRefs(store)
    let linkVisable = ref(false) 
    let total = ref(0)
    let beforeStep = () => {
        // 上一步
        activeIndex.value --
    }
    let nextStep = () => {
        activeIndex.value ++
    }
    let openWebsocket = () => {
      linkVisable.value = true
      stepVisable.value = true
        //  proxy.$message({showClose: true,message: "目前还不能联网",type: "warning"})
    }
    let closeWebsocket = () => {
        isWatch.value = false 
        // @ts-ignore
        websocket.value.close()
    }
    // 关闭对话框
    const closeDialog = () => {
        stepVisable.value = false
    }
    // 确定连接
    let confirmLink = async () => {
        if (linkCode.value === '') {
            await proxy.$message({showClose: true,message: "连接码不能为空",type: "warning"})
        } else if(!(/^[a-zA-Z0-9]{6,12}$/.test(linkCode.value))) {
            await proxy.$message({showClose: true,message: "连接码为6-12位，由数字和字母组成",type: "warning"})
        } else {
           activeIndex.value = 3
           linkVisable.value = false
           await proxy.$message({showClose: true,message: "连接成功",type: "success"})
           setTimeout(() => {
            activeIndex.value = 1
            stepVisable.value = false
           },1000)
           isWatch.value = true
            let socket = new WebSocket("ws://megasensing.cn:9999")
            // 建立连接
            socket.onopen = function() {
                let initInfo = {action: 'init',linkCode:linkCode.value,token:store.userInfo.token,deviceName: store.userInfo.username}
                socket.send(JSON.stringify(initInfo))
            }
            socket.onmessage = function(msg) {
                try {
                    let data = JSON.parse(msg.data)
                    if (data.action === 'getAllDevice') {
                        deviceList.value = data.data
                        total.value = data.data.length
                    }
                } catch(err) {
                    console.log(err)
                }
            }
            socket.onclose = function() {
                isWatch.value = false
                deviceList.value = []
                console.log("连接关闭")
            }
            //@ts-ignore
            websocket.value = socket
        }
    }
    // 断开设备连接
    const closeLink = (deviceName) => {
        console.log(deviceName)
        websocket.value.send(JSON.stringify({action:"removeDevice",deviceName}))
    }
</script>

<style scoped lang="less">
    .tool {
        margin-top: 10px;
    }
    .el-step {
        margin-top: 10px;
    }
    .el-table {
        margin-top: 10px;
    }
</style>